package top.gbiot.config;

import com.alibaba.fastjson.JSON;
import lombok.Getter;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import top.gbiot.scan.entity.ApiTemplate;
import top.gbiot.scan.entity.DeviceTemplate;
import top.gbiot.scan.service.IoTableService;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

@Component
public class DeviceTemplateConfig {

    //设备特征模板文件目录
    @Value("${hs.deviceFeaturePath}")
    private String deviceFeaturePath;

    //特征文件扩展名
    @Value("${hs.fileExt}")
    private String fileExt;

    @Autowired
    IoTableService ioTableService;

    private final List<String> features = new ArrayList<>();

    @Getter
    public final List<DeviceTemplate> DeviceTemplateList = new ArrayList<>();

    //api 关键字的模板
    public List<ApiTemplate> apiTemplateList = new ArrayList<>();

    //加载设备特征模板文件
    private void getFiles(String folderPath){
        File folder = new File(folderPath);
        if ( !folder.exists() || !folder.isDirectory()) {
            System.out.println("未发现设备特征库路径！");
            return;
        }

        searchFilesRecursively(folder);

//        File[] files = folder.listFiles();
//        if ( null == files ) {
//            System.out.println("未发现设备特征文件！");
//            return;
//        }
//
//        for ( File file: files) {
//            if (file.isFile()) features.add( file.getAbsolutePath()) ;
//        }
    }

    //递归搜索文件
    private void searchFilesRecursively(File dir) {
        File[] files = dir.listFiles();
        if (files == null) {
            System.out.println("未发现设备特征文件！");
            return;
        }

        for (File file : files) {
            String ext =  FilenameUtils.getExtension(file.getName());
            if (file.isFile() && ext.contains( fileExt) ) {
                features.add(file.getAbsolutePath());
            } else if (file.isDirectory()) {
                searchFilesRecursively(file);
            }
        }
    }

    public void loadDeviceFeature() throws IOException {

        //数据库中创建临时设备模板表
        ioTableService.createTemplateTable();

        //设备模板表存在就清空表
        ioTableService.truncateTemplate();

        //清空
        DeviceTemplateList.clear();
        apiTemplateList.clear();

        String currentPath = System.getProperty("user.dir")+deviceFeaturePath;
        System.out.println("路径信息："+ currentPath+", "+fileExt);
        getFiles(currentPath);
        if (features.isEmpty()) {
            System.out.println("库文件空！");
        } else {
            System.out.println("库文件如下：");
            for ( String f :features) {
                System.out.println(f);
                DeviceTemplate dt = parseFeature(f);
                if ( null != dt.getBrand() && null!= dt.getName() ||null!=dt.getModel() ) {
                    ioTableService.insertTemplate( dt );
                    DeviceTemplateList.add(dt); //模板匹配 api
                    boolean findApiStr=false;
                    for (ApiTemplate atp : apiTemplateList) {
                        String s1= atp.getApiInterface().trim();
                        String s2= atp.getApiProto().trim();
                        String s3 =atp.getRequestMethod().trim();
                        String s11 = dt.getApiInterface().trim();
                        String s12 = dt.getApiProto().trim();
                        String s13 = dt.getRequestMethod().trim();
                        if (s1.equals(s11)&&s2.equals(s12) && s3.equals(s13)) {
                            //接口关键字重复出现
                            findApiStr =true;
                            break;
                        }
                    }
                    if (!findApiStr) {
                        //写接口关键字
                        ApiTemplate atp = new ApiTemplate();
                        atp.setApiInterface(dt.getApiInterface().trim());
                        atp.setApiProto(dt.getApiProto().trim());
                        atp.setRequestMethod(dt.getRequestMethod().trim());
                    }

                }


            }
        }


    }

    private DeviceTemplate parseFeature(String file) throws IOException {

        //读取JSON文件内容
        String jsonStr =  new String(Files.readAllBytes(Paths.get(file)));

        //转换为Java对象
        DeviceTemplate dt = JSON.parseObject(jsonStr, DeviceTemplate.class);
        System.out.println("json内容" + dt);

        return  dt;

    }


}
